// ProfileScreen.kt
package com.example.nutritionmanager.profile

import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.nutritionmanager.R
import com.example.nutritionmanager.viewModels.UserProfileState
import com.example.nutritionmanager.viewModels.UserProfileViewModel
import com.example.nutritionmanager.buttons.PrimaryButton
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.material.SnackbarHostState
import androidx.compose.ui.platform.LocalContext
import com.example.nutritionmanager.UserProfile
import com.example.nutritionmanager.record.MealType
import com.example.nutritionmanager.record.NutritionRecordActivity
import java.time.Instant
import java.time.LocalDate
import java.time.temporal.ChronoUnit

@Composable
fun ProfileScreen(navController: NavController, userProfileViewModel: UserProfileViewModel = hiltViewModel()) {
    val userProfileState by userProfileViewModel.userProfileState.collectAsState()

    val snackbarHostState = remember { SnackbarHostState() }
    val context = LocalContext.current

    // 在Composable首次启动时获取用户资料
    LaunchedEffect(Unit) {
        userProfileViewModel.fetchUserProfile()
    }

    // 监听错误信息并通过Snackbar展示
    LaunchedEffect(userProfileState) {
        if (userProfileState is UserProfileState.Error) {
            val errorMessage = (userProfileState as UserProfileState.Error).error
            snackbarHostState.showSnackbar(errorMessage)
        }
    }

    // 整个页面可上下滑动，并包含Snackbar
    Box(
        modifier = Modifier
            .fillMaxSize()
//            .background(Color(0xFFf1f1f1))
            .background(color = MaterialTheme.colorScheme.background)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState()) // 使页面可滑动
                .padding(16.dp) // 页面内容的内边距
        ) {
            when (userProfileState) {
                is UserProfileState.Loading -> {
                    // 显示加载中的进度条
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(100.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }

                is UserProfileState.Success -> {
                    val userProfile = (userProfileState as UserProfileState.Success).userProfile
                    Text(
                        text = "我的",
                        fontSize = 22.sp,
                        color = MaterialTheme.colorScheme.onSurface,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                    // 用户名
                    Text(
                        text = userProfile.username,
                        style = MaterialTheme.typography.headlineSmall,
                        color = MaterialTheme.colorScheme.onSurface,
                        modifier = Modifier.padding(bottom = 20.dp)
                    )
                    // 注册天数
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(bottom = 20.dp)
                    ) {
                        Text(
                            text = "您已注册${calculateRegistrationDays(userProfile.registerDate)}天啦",
                            modifier = Modifier.align(Alignment.CenterEnd).padding(end = 10.dp), // 设置文本靠右对齐
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }

                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(16.dp),
                        elevation = CardDefaults.cardElevation(4.dp),
                        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                    ) {
                        ProfileItem(label = "个人资料", resourceId = R.drawable.user_info, onClick = {
                            val intent = Intent(context, ProfileSecondaryActivity::class.java).apply {
                                putExtra("profile_type", ProfileType.PROFILE_TYPE_INFO)
                            }
                            context.startActivity(intent)
                        })
                        Divider(color = Color.LightGray, thickness = 1.dp)
                        ProfileItem(label = "我的数据", resourceId = R.drawable.user_data, onClick = { /* TODO: 处理我的数据点击 */ })
                    }

                    Spacer(modifier = Modifier.height(16.dp))

                    Card(
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(16.dp),
                        elevation = CardDefaults.cardElevation(4.dp),
                        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                    ) {
                        ProfileItem(label = "隐私协议", resourceId = R.drawable.privacy, onClick = { /* TODO: 处理隐私协议点击 */ })
                        Divider(color = Color.LightGray, thickness = 1.dp)
                        ProfileItem(label = "关于", resourceId = R.drawable.about, onClick = { /* TODO: 处理关于点击 */ })
                        Divider(color = Color.LightGray, thickness = 1.dp)
                        ProfileItem(label = "设置", resourceId = R.drawable.setting, onClick = {
                            val intent = Intent(context, ProfileSecondaryActivity::class.java).apply {
                                putExtra("profile_type", ProfileType.PROFILE_TYPE_SETTING)
                            }
                            context.startActivity(intent)
                        })
                    }

                    Spacer(modifier = Modifier.height(16.dp))

                    // 退出登录按钮
                    PrimaryButton(
                        onClick = {
                            userProfileViewModel.clearUserProfile()
                            navController.navigate("login") {
                                // 清除后退栈，防止用户按返回键返回
                                popUpTo("profile") { inclusive = true }
                            }
                        },
                        modifier = Modifier.fillMaxWidth(),
                        text = "退出登录"
                    )
                }

                is UserProfileState.Error -> {
                    // 已在上方通过Snackbar展示错误信息
                    // 可以在此处添加额外的错误处理 UI
                }

                is UserProfileState.Idle -> {
                    // 初始状态，可以显示一个空界面或提示
                }
            }
        }

//        // Snackbar
//        SnackbarHost(
//            hostState = snackbarHostState,
//            modifier = Modifier.align(Alignment.BottomCenter)
//        )
    }
}

// 添加日期计算扩展函数
fun calculateRegistrationDays(registerDateString: String): Int {
    val registerDate = LocalDate.parse(registerDateString)
    val currentDate = LocalDate.now()
    return ChronoUnit.DAYS.between(registerDate, currentDate).toInt()
}